import { Component, OnInit } from '@angular/core';
import { MdlSnackbarService } from '@angular-mdl/core';
import { ConfirmationService, TreeNode, DialogService } from 'primeng/primeng';
import { flyIn } from '../../common/animation/common.animation';
import { ResourceService } from './service/resource.service';
import { ResourceDetailComponent } from './resource-detail.component';

@Component({
  templateUrl: './resource.component.html',
  styleUrls: ['./resource.component.scss'],
  providers: [ResourceService],
  animations: [flyIn]
})
export class ResourceComponent implements OnInit {
  loading: boolean = true;
  systems: TreeNode[];
  selectedNode: TreeNode;
  suggestions: TreeNode[];
  suggestion: TreeNode;

  visible: boolean = false;
  resources: TreeNode[];
  selectedResource: TreeNode;

  constructor(
    private resourceService: ResourceService,
    private dialogService: DialogService,
    private mdlSnackbarService: MdlSnackbarService,
    private confirmationService: ConfirmationService) { }

  ngOnInit() {
    /**初始化树选择器 */
    this.resourceService.getSystemTree().subscribe(data => {
      this.loading = false;
      this.systems = data;
      if (this.systems[0].children.length > 0) {
        this.selectedNode = this.systems[0].children[0];
        this.nodeSelect();
      }
    });
  }

  //树节点选中事件
  nodeSelect() {
    this.resourceService.loadResourcesBySysId(+this.selectedNode["id"]).subscribe(resources => {
      this.visible = false;
      this.resources = resources;
    });
  }

  //节点快速查找
  search(event) {
    this.suggestions = this.getSuggestionRecursive(event.query, this.systems, []);
  }

  //查找选中事件
  selectSuggestion() {
    this.selectedNode = this.suggestion;
    this.recursiveExpandNode(this.systems[0].children, this.selectedNode);
    this.nodeSelect();
  }
  //资源查找时辅助关闭其他资源信息
  recursiveExpandNode(nodes: TreeNode[], dest: TreeNode) {
    nodes.forEach(ele => {
      if (dest.data['code'].indexOf(ele.data['code']) != -1) {
        ele.expanded = true;
        this.recursiveExpandNode(ele.children, dest);
      } else {
        ele.expanded = false;
      }
    });
  }
  //查找过滤
  getSuggestionRecursive(query: string, nodes: TreeNode[], dest: TreeNode[]) {
    nodes.forEach(node => {
      if (node.children) {
        node.children.forEach(childNode => {
          if (childNode.label.indexOf(query) != -1) {
            dest.push(childNode);
          }
        });
        this.getSuggestionRecursive(query, node.children, dest);
      }
    });
    return dest;
  }

  /** 删除 */
  delete($event) {
    if (this.selectedResource) {
      this.confirmationService.confirm({
        header: '确认',
        message: '您确定要删除选择的记录吗？',
        accept: () => {
          this.resourceService.deleteResourceById(this.selectedResource["id"])
            .subscribe(data => {
              this.resourceService.loadResourcesBySysId(+this.selectedNode["id"]).subscribe(resources => this.resources = resources);
              this.mdlSnackbarService.showToast('数据删除成功！');
            });
        }
      });
    }
  }

  /** 编辑 */
  update($event) {
    if (this.selectedResource) {
      const ref = this.dialogService.open(ResourceDetailComponent, {
        header: '编辑资源',
        width: '600px',
        contentStyle: { 'height': '350px', 'padding': '0' },
        data: {
          'id': this.selectedResource['id']
        }
      });
      ref.onClose.subscribe(data => {
        if (data) {
          this.nodeSelect();
          this.mdlSnackbarService.showToast("资源保存成功！");
        }
      });
    }
  }

  /** 新增子资源 */
  addChildren($event) {
    const ref = this.dialogService.open(ResourceDetailComponent, {
      header: '新增子资源',
      width: '600px',
      contentStyle: { 'height': '350px', 'padding': '0' },
      data: {
        'id': (this.selectedResource ? this.selectedResource['id'] : 0), 'sysId': +this.selectedNode["id"]
      }
    });
    ref.onClose.subscribe(data => {
      if (data) {
        this.nodeSelect();
        this.mdlSnackbarService.showToast("资源保存成功！");
      }
    });
  }

  /**节点选中事件  */
  resNodeSelect($event) {
    this.visible = true;
  }
}
